<?php 
session_start();

// 如果检测到已登录，直接跳转至首页
if (isset($_SESSION["username"])) {
    if ($_SESSION["admin"]=="1"){
        echo "<h4>管理员创建子账号</h4>";
    }else{
        header("Location:index.php");
        exit();
    }
}
?>
<!DOCTYPE unspecified PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"></meta>
<title>注册</title>
<script language="JavaScript">
function InputCheck(form1)
{
  if (form1.password.value == "")
    {
    alert("请输入昵称。");
    form1.password.focus();
    return (false);
  }
  if (form1.password.value == "")
  {
    alert("请输入密码。");
    form1.password.focus();
    return (false);
  }
}
</script>
</head>
<body>
	<h3>用户注册</h3>
	<p>
	<input type="button" onclick="window.location.href='index.php'"
		value="首页" />
	</p>
	<form method="post" action="sign.php"
		onSubmit="return InputCheck(this)">
		<p>
		昵 称: <input name="username" type="text" value="" /></p><p> 密 码: <input
			name="password" type="password" value="" /></p>
			<?php 
			if ($_SESSION["username"]=="admin"){
			    ?>
			    <p>是否设定为管理员:<input name="chooseadmin" type="checkbox" value="1" /></p>
			    <?php 
			}else 
			?>
			    <?php
			?>
			<input type="button" onclick="history.go(-1)"
			value="返回"><input
			name="submit" type="submit" value="注册" />
	</form>
<?php
if ($_POST) {
    require './core/conn.php';
    date_default_timezone_set("PRC");
    $createtime = time();
    $username = $_POST['username'];
    $select_sql = mysqli_query($conn, "SELECT count(*) FROM user WHERE `username`='$username'");
    $count_array = mysqli_fetch_array($select_sql);
    if ($count_array['count(*)'] == 1) {
        echo '改昵称已被注册！';
    }else{
        $password = MD5(trim($_POST['password']));
        if (!isset($_POST['chooseadmin'])){
            $chooseadmin=0;
        }else{
            $chooseadmin=$_POST['chooseadmin'];
        }
        $insert_sql = "INSERT INTO user(username, password, createtime ,admin)VALUES('$username','$password',$createtime,$chooseadmin)";
        if (mysqli_query($conn, $insert_sql)) {
            echo "<p></p>";
            echo '注册成功！';
            ?>
        <input type="button" onclick="window.location.href='login.php'"
		value="立即登录" />
<?php
        } else {
            echo '注册失败：', mysqli_error(), '[ <a href="javascript:history.back()">返 回</a> ]';
        }
    }
}
?>